package com.o2opuzi.lib.http;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.StatusLine;
import org.springframework.util.SerializationUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 返回结果
 * @author Y.hj
 * @date 2016年5月31日
 */
public class HttpResult{
	
	private static Log log = LogFactory.getLog(Http.class);
	
	private Integer resultCode;
	
	private StatusLine statusLine;
	
	private Header[] headers;
	
	private byte[] resultData;
	
	
	/**
	 * 把结果集装换成 map 对象
	 * @auther Y.hj
	 * @return
	 */
	public Map<String, Object> toMap(){
		return toJsonObject(Map.class);
	}
	
	
	/**
	 * 结果返回 bytes
	 * @return
	 */
	public byte[] toBytes(){
		return this.resultData;
	}
	
	/**
	 * 返回 String
	 * @return
	 */
	public String toString(){
		try {
			return new String(this.resultData, "utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}
	
	public JSONObject toJsonObject(){
		return JSON.parseObject(toString());
	}
	
	@SuppressWarnings("unchecked")
	public <T> T toJsonObject(Class<?> clazz){
		try {
			return (T) JSON.parseObject(toString(), clazz);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public <T> T toObject(){
		try {
			return (T) SerializationUtils.deserialize(toBytes());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	public HttpResult(StatusLine statusLine,Header[] headers,byte[] resultBytes) {
		super();
		this.statusLine = statusLine;
		this.headers = headers;
		this.resultCode = statusLine.getStatusCode();
		this.resultData = resultBytes;
	}

	public Integer getResultCode() {
		return resultCode;
	}

	public void setResultCode(Integer resultCode) {
		this.resultCode = resultCode;
	}


	public StatusLine getStatusLine() {
		return statusLine;
	}


	public void setStatusLine(StatusLine statusLine) {
		this.statusLine = statusLine;
	}


	public Header[] getHeaders() {
		return headers;
	}


	public void setHeaders(Header[] headers) {
		this.headers = headers;
	}
	
}
